package com.gzc.just.play.last.war.common.handler;

import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息处理器管理器
 * 负责管理和分发消息处理器
 */
public class MessageHandlerManager {
    private static final Logger logger = LoggerFactory.getLogger(MessageHandlerManager.class);
    
    // 服务器类型
    private final VirtualThreadServerFramework.ServerType serverType;
    
    // 消息处理器映射表
    private final ConcurrentHashMap<Integer, SimpleMessageHandler> handlers = new ConcurrentHashMap<>();
    
    // 消息名称映射表（用于日志）
    private final ConcurrentHashMap<Integer, String> messageNames = new ConcurrentHashMap<>();
    
    /**
     * 构造函数
     * @param serverType 服务器类型
     */
    public MessageHandlerManager(VirtualThreadServerFramework.ServerType serverType) {
        this.serverType = serverType;
        initializeMessageNames();
        logger.info("Initialized MessageHandlerManager for server: {}", serverType.getName());
    }
    
    /**
     * 初始化消息名称映射表
     */
    private void initializeMessageNames() {
        // 根据服务器类型初始化不同的消息名称
        switch (serverType) {
            case GATE_SERVER:
                // Gate Server 消息
                messageNames.put(8193, "AskLogin");
                messageNames.put(8194, "AskReconnectGame");
                messageNames.put(8195, "AskComleteUserInfo");
                messageNames.put(8196, "AskUserGameInfo");
                break;
                
            case LOGIN_SERVER:
                // Login Server 消息
                messageNames.put(1, "LoginRequest");
                messageNames.put(2, "LogoutRequest");
                messageNames.put(3, "RegisterRequest");
                break;
                
            case BALANCE_SERVER:
                // Balance Server 消息
                messageNames.put(1001, "ServerStatus");
                messageNames.put(1002, "LoadBalance");
                messageNames.put(1003, "ServerList");
                break;
                
            case CENTRAL_SERVER:
                // Central Server 消息
                messageNames.put(2001, "CentralCommand");
                messageNames.put(2002, "ServerInfo");
                messageNames.put(2003, "GlobalAnnouncement");
                break;
                
            case SCENE_SERVER:
                // Scene Server 消息
                messageNames.put(3001, "CreateBattle");
                messageNames.put(3002, "JoinBattle");
                messageNames.put(3003, "LeaveBattle");
                messageNames.put(3004, "BattleAction");
                break;
        }
    }
    
    /**
     * 注册消息处理器
     * @param handler 消息处理器
     */
    public void registerHandler(SimpleMessageHandler handler) {
        if (handler == null) {
            logger.warn("Attempted to register null handler for server: {}", serverType.getName());
            return;
        }
        
        int messageId = handler.getMessageId();
        handlers.put(messageId, handler);
        
        String messageName = messageNames.getOrDefault(messageId, "Unknown");
        logger.info("Registered message handler: {} for message: {} (ID: {}) in server: {}", 
                   handler.getName(), messageName, messageId, serverType.getName());
    }
    
    /**
     * 获取消息处理器
     * @param messageId 消息ID
     * @return 消息处理器，如果没有找到则返回null
     */
    public SimpleMessageHandler getHandler(int messageId) {
        return handlers.get(messageId);
    }
    
    /**
     * 获取消息名称
     * @param messageId 消息ID
     * @return 消息名称，如果没有找到则返回"Unknown"
     */
    public String getMessageName(int messageId) {
        return messageNames.getOrDefault(messageId, "Unknown");
    }
    
    /**
     * 检查是否有指定消息的处理器
     * @param messageId 消息ID
     * @return 是否有处理器
     */
    public boolean hasHandler(int messageId) {
        return handlers.containsKey(messageId);
    }
    
    /**
     * 获取已注册的处理器数量
     */
    public int getHandlerCount() {
        return handlers.size();
    }
    
    /**
     * 处理消息
     * @param messageId 消息ID
     * @param messageData 消息数据
     * @param ctx Netty通道上下文
     */
    public void processMessage(int messageId, byte[] messageData, ChannelHandlerContext ctx) {
        SimpleMessageHandler handler = handlers.get(messageId);
        if (handler != null) {
            try {
                handler.handle(messageData, ctx);
            } catch (Exception e) {
                logger.error("Error processing message: {} for server: {}", 
                          messageId, serverType.getName(), e);
            }
        } else {
            logger.warn("No handler found for message: {} for Server: {}", 
                       messageId, serverType.getName());
        }
    }
    
    /**
     * 获取服务器类型
     */
    public VirtualThreadServerFramework.ServerType getServerType() {
        return serverType;
    }
}